package com.migu.rbac.service;

import com.migu.rbac.message.RbacMessageService;
import com.migu.rbac.model.SysUser;
import com.migu.rbac.proxy.PromactityProxy;
import com.migu.rbac.util.MD5Util;
import com.migu.rbac.util.TokenProvider;
import com.migu.rbac.vo.ErrorCodes;
import com.migu.rbac.vo.MsgRes;
import com.migu.rbac.vo.Response;
import com.migu.rbac.vo.ResultResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO : 登录业务
 * @Author: zj
 * @Date: 15:22 2019/5/29
 * @Version 1.0
 **/
@Service
public class AuthService {

    private static final Logger log = LoggerFactory.getLogger(AuthService.class);

    @Value("${sendmessage.switch}")
    private String MSG_SWITCH;

    @Value("${security.jwt.header}")
    private String AUTHORIZATION_HEADER;//"Authorization"
    @Value("${security.jwt.bearer-header}")
    private String BEARER_HEADER;//"Bearer "

    @Value("${security.jwt.secret-key}")
    private String secretKey;

    @Value("${security.jwt.refresh-limit-times}")
    private int refreshLimitTimes;

    @Value("${security.jwt.ahead-time}")
    private int aheadTime;

    @Value("${security.verify-code}")
    private String isVerify;
    @Autowired
    private SysUserService userService;

    @Autowired
    private TokenProvider tokenProvider;

    @Autowired
    private RbacMessageService rbacMessageService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PromactityProxy promactityProxy;

    @Value("${sendmessage.message-template}")
    private String MSG_TEMPLATE;


    //用户登录
    public Response login(String loginName, String password, String verification) {
        SysUser user = userService.findByloginName(loginName);
        if (user == null) {
            return Response.error(ErrorCodes.LOGINNAME_NOT_EXIST.getCode(), ErrorCodes.LOGINNAME_NOT_EXIST.getDesc());
        }
        if (!user.getPassword().equals(MD5Util.encode(password))) {
            return Response.error(ErrorCodes.PASSWORD_WRONG.getCode(), ErrorCodes.PASSWORD_WRONG.getDesc());
        }
        //是否需要验证码
        if ("enable".equals(isVerify)) {

            String phoneNumber = user.getPhone();
            if (MSG_SWITCH.equals("new")) {
                Map<String, String> resMap = promactityProxy.checkMessage(phoneNumber, verification);
                if (!"success".equals(resMap.get("message"))) {
                    log.info("营销平台验证失败>>>>>>>>>手机号:" + phoneNumber + ">>>>>>>>>>>输入验证码:" + verification);
                    return Response.error(ErrorCodes.VERIFICATION_WRONG);
                }

            } else {
                StringBuffer msgKey = new StringBuffer().append(user.getPhone()).append(user.getId());//验证码存储在redis中的key
                String msgValue = (String) redisTemplate.opsForValue().get(msgKey.toString());
                log.info("msgValue:" + msgKey.toString() + ",verification" + verification);
                if (!verification.equals(msgValue)) {
                    return Response.error(ErrorCodes.VERIFICATION_WRONG.getCode(), ErrorCodes.VERIFICATION_WRONG.getDesc());
                }
                redisTemplate.delete(msgKey.toString());
                log.info("del msgKey:" + msgKey.toString());
            }
        }
        String userName = user.getLoginname();
        String userId = String.valueOf(user.getId());
        String jwt = tokenProvider.createToken(userId, userName, 0);
        String authToken = BEARER_HEADER + jwt;
        log.info("authToken:" + authToken);
        //*******************************
        // 将JWT写入浏览器的Http Header中
        //*******************************         ff
        this.response.addHeader(AUTHORIZATION_HEADER, authToken);
        Map<String, Object> map = new HashMap<>();
        map.put("userName", userName);
        map.put("authToken", authToken);
        map.put("userId", userId);
        return Response.success(map);
    }


    //发送短信验证码
    public Response sendMessage(String loginName, String password) {
        String userId = "";
        String phoneNumber = "";
        //判断用户名和密码的正确性
        if (!StringUtils.isEmpty(loginName) && !StringUtils.isEmpty(password)) {
            SysUser user = userService.findByloginName(loginName);
            //判断用户是否存在
            if (user == null) {
                return Response.error(ErrorCodes.LOGINNAME_NOT_EXIST.getCode(), ErrorCodes.LOGINNAME_NOT_EXIST.getDesc());
            } else {
                userId = String.valueOf(user.getId());
            }
            log.info("password:" + user.getPassword());
            //判断密码是否正确
            if (!user.getPassword().equals(MD5Util.encode(password))) {
                return Response.error(ErrorCodes.PASSWORD_WRONG.getCode(), ErrorCodes.PASSWORD_WRONG.getDesc());
            }
            phoneNumber = user.getPhone();
        }
        log.info("phoneNumber:" + phoneNumber);
        //判断手机号码是否存在
        MsgRes msg = null;
        if (!StringUtils.isEmpty(phoneNumber)) {
            //使用营销平台短信接口
            if (MSG_SWITCH.equals("new")) {
                //使用营销平台短信接口
                Map<String, String> resMap = promactityProxy.sendMessage(phoneNumber);
                String message = resMap.get("message");
                log.info("发送验证码message:" + message);
                if ("success".equals(message)) {
                    return Response.success();
                } else if ("fail".equals(message)) {
                    String code = resMap.get("code");
                    //发送达到次数限制
                    if ("4001".equals(code)) {
                        return Response.error(ErrorCodes.SEND_MSG_UPPER_LIMIT);
                    }
                    //发送失败
                    else {
                        return Response.error(4002, message);
                    }
                }
            } else {
                try {
                    msg = rbacMessageService.sendMsg(phoneNumber, userId, MSG_TEMPLATE);
                    if (!("01").equals(msg.getCode())) {
                        return Response.error(Integer.valueOf(msg.getCode()), msg.getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            return Response.error(ErrorCodes.PHONENUMBER_NOT_EXIST.getCode(), ErrorCodes.PHONENUMBER_NOT_EXIST.getDesc());
        }
        return Response.success(msg);
    }


}